package com.yangxd.hospital.service.auth;

import com.yangxd.hospital.entity.Role;
import com.yangxd.hospital.entity.RoleUser;
import com.yangxd.hospital.service.RoleService;
import com.yangxd.hospital.service.RoleUserService;
import com.yangxd.hospital.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: yangxudong
 * @Date: 2021/4/24 20:53
 * @Version 1.0
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleUserService roleUserService;

    @Autowired
    private RoleService roleService;

    /**
     * 通过用户名称查询用户信息
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if(userName == null || "".equals(userName) ) {
            throw new RuntimeException("用户名称不能为空");
        }
        //如果不为空，通过用户名查询用户
        com.yangxd.hospital.entity.User user = userService.selectByName(userName);
        if(user == null) {
            throw new UsernameNotFoundException(String.format("%s这个人不存在",userName));
        }
        //如果存在则查询该用户具有的角色
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //
        List<RoleUser> roleUserList = roleUserService.listByUserId(user.getUserId());
        roleUserList.forEach(roleUser -> {
                    Role role = roleService.selectByRoleId(roleUser.getRoleId());
                    authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
                }
        );
        return new User(user.getUserName(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);
    }
}
